// pages/index/task_detail.js
//获取应用实例
var msg = require("../../../siteinfo.js");
const app = getApp()
var select = []
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const innerAudioContext_con = wx.createInnerAudioContext()
var tempFilePath;
var list = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSpeaking: false,
    my_answer: false,
    recording: true,
    index: 0,
    pause:false,
    answerState: 0,
    hide:false,
    btn:"录音",
    already:false,
    start_btn:true,
    audio_play:false,
    audio_pause:false,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(select)
    var that = this;
    // —————————————— 获取网址——————————
    app.util.request({
      url: "entry/wxapp/Attachurl",
      'cachetime': '0',
      success: function (res) {
        that.setData({
          url: res.data
        })
      }
    })

    //作业详情的id
    var task_id = options.task_id

    //从缓存里面取出所有列表的数据
    var all = wx.getStorageSync('all_list')
    console.log(all)

    var index = that.data.index
    var page = parseFloat(index) + 1
    // console.log(options)
    // console.log(that)
    // console.log(task_id)
    that.setData({
      task_id: task_id,
      index: index,
      page: page,
      all: all,
      all_length: all.length
    })

    that.detail()
  },

  detail: function (e) {
    var that = this;
    // console.log(that)
    var all = that.data.all
    var index = that.data.index
    var task_id = all[index].id
    app.util.request({
      url: "entry/wxapp/TaskDetali",
      'cachetime': '0',
      data: {
        task_id: task_id
      },
      success: function (res) {
        console.log("作业详情")
        console.log(res)
        if (res.data.code == 200) {
          that.setData({
            task: res.data.list[0],
            none: res.data,
            length: res.data.list[0].voice.length,
          })
        } else {
          that.setData({
            none: res.data
          })
        }
      }
    })
  },

  /*点击下一题 */
  onNext: function (e) {
    var that = this;
    var index = that.data.index
    var page = that.data.page
    that.setData({
      btn: "开始答题"
    })
    console.log(select.length)
    if (select.length != page) {
      wx.showModal({
        title: '提示',
        content: '当前这道题答完,才能回答下一题',
      })
    } else {
      that.setData({
        index: Number(that.data.index) + 1,
        page: Number(that.data.page) + 1,
        my_answer: false,
        recording: true
      })
      that.detail()
    }
  },

  //开始录音的时候
  handleTouchStart: function (e) {
    console.log(e)
    var that = this
    innerAudioContext_con.pause();
    this.videoContext.pause()
    that.setData({
      hide:true,
      start_btn:false,
    })

    //判断是否授权
    wx.getSetting({
      success(res) {
        console.log(res)
        if (!res.authSetting['scope.record']) {
          console.log("没有授权z偶")
          that.setData({
            isSpeaking: false,
          }),
          wx.authorize({
            scope: 'scope.record',
            success() {
              console.log("授权成功")
               that.vioce()
            },
            fail() {
              console.log("拒接授权");
              wx.showModal({
                title: '提示',
                content: '您未授权录音,不能录音',
                success: function (res) {
                  console.log(res)
                  if (res.confirm) {
                    //确认则打开设置页面
                    wx: wx.openSetting({
                      success: function (res) {
                        console.log(res)
                      },
                      fail: function (res) {
                        console.log(res)                       
                      },
                      complete: function (res) { },
                    })
                  } else {
                    console.log("取消则返回上一页")
                    //取消则返回上一页
                    wx.navigateBack({
                      delta: 1
                    })
                  }
                },
              })
            }
          })
        } else {
          that.vioce()
        }
      },
      fail:function(res){
        console.log(res)
      }
    })
  },

  //获取录音
  vioce: function (e) {
    var that=this;
    //当前题目的id
    // var current_id = that.data.task.id
    // console.log("当前题目的id:" + current_id)
    var myDates = new Date()
    var start_min = myDates.getMinutes(); //获取当前分钟数(0-59)
    var start_miao = myDates.getSeconds(); //获取当前秒数(0-59)
    var start_time = start_min * 60 + start_miao
    // console.log("分钟:" + start_min + "" + "秒:" + start_miao)
    // console.log(start_time)
    // console.log(that)
    //显示话筒
    that.setData({
      isSpeaking: true,
      start_time: start_time
    })

    const options = {
      duration: 60000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 500,//指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart((res) => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError(res => {
      console.log(res);
    })
  },

  //停止录音
  handleTouchEnd: function (e) {
    console.log(e)
    var that = this;
    var start_btn = that.data.start_btn
    if (start_btn==false){
      //当前题目的id
      var current_id = that.data.task.id
      console.log("当前题目的id:" + current_id)
      var user_id = wx.getStorageSync('user_msg').id
      console.log(user_id)
      that.setData({
        hide: false,
        btn: "重答",
        start_btn:true
      })
      var start_times = that.data.start_time;
      var myDate = new Date()
      var end_min = myDate.getMinutes(); //获取当前分钟数(0-59)
      var end_miao = myDate.getSeconds(); //获取当前秒数(0-59)
      // console.log("分钟:" + end_min + "" + "秒:" + end_miao)
      var end_time = end_min * 60 + end_miao
      var min_time = end_time - start_times
      // console.log(end_time)
      //隐藏话筒
      that.setData({
        isSpeaking: false,
        min_time: min_time,
        my_answer: true
      }),
      recorderManager.stop();
      recorderManager.onStop((res) => {
        this.tempFilePath = res.tempFilePath;
        // console.log('停止录音', res.tempFilePath)
        const { tempFilePath } = res
        var data = res.tempFilePath
        console.log(res.tempFilePath)
        that.setData({
          my_audio: res.tempFilePath
        })

        //判断是否有重复的录音
        var sourt = {
          id: current_id,
          value: res.tempFilePath,
          user_id: user_id,
          answer_time:that.data.min_time
        }
        var recording = that.data.recording
        console.log(recording)
        if (recording == true) {
          select = select.concat(sourt)
          console.log("没有重复录音")

          console.log(select)
          that.setData({
            select: select,
            recording: false
          })
        } else {
          for (let i in select) {
            console.log(current_id)
            if (select[i].id == current_id) {
              console.log('有重复的录音')
              select[i] = sourt
              console.log(select)
              that.setData({
                select: select,
                recording: false
              })
            }
          }
        }
      })
    }
  },

  upload: function (data) {
    console.log(data)
    var u_id = wx.getStorageSync('user_msg').id

    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    console.log(data.path[i])
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i].value,
      name: 'upfile',
      formData: null,
      success: (resp) => {
        if (resp.data != '') {
          success++;
          var arr = {
            id: data.path[i].id,
            value: resp.data,
            u_id: u_id,
            answer_time: data.path[i].answer_time,
          }
          list.push(arr)
          console.log(list)
          if (list.length == select.length) {
            that.submit()
          }
        }
        else {
          wx.showToast({
            icon: "loading",
            title: "请重试"
          })
        }
      },
      fail: (res) => {
        fail++;
        //console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        //console.log(i);
        i++;
        if (i == data.path.length) {
          that.setData({
            images: data.path
          });
          wx.hideToast();
          //console.log('执行完毕');
          // console.log('成功：' + success + " 失败：" + fail);
        } else {
          //console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.upload(data);
        }

      }
    });
  },

  /*点击提交 */
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    var user_id = wx.getStorageSync('user_msg').id
    var that = this;
    console.log(that)
    console.log("点击提交")

    that.upload({
      url: msg.siteroot + '?i=' + msg.uniacid + '&c=entry&a=wxapp&do=UploadFiles&m=zh_jypx',
      path: select
    });

  },
  submit: function (e) {
    console.log(list)
    var that=this;
      app.util.request({
        "url": "entry/wxapp/SubmitTask",
        'cachetime': '0',
        data: {
          select: list
        },
        success: function (res) {
          console.log(res)
          // var all = wx.getStorageSync('all_list')

          wx.showToast({
            title: '提交成功',
            icon: 'none',
            duration: 1000
          })
          setTimeout(function () {
            wx: wx.redirectTo({
              url: "index",
            })
          }, 1000)
        },
        fail: function (res) {
          console.log(res)
          wx.showToast({
            title: '提交失败',
            icon: 'none',
            duration: 1000
          })
          setTimeout(function () {
            wx: wx.redirectTo({
              url: "data_list",
            })
          }, 1000)
        }
      })    
  },

  //播放我的回答
  audioPlay: function () {
    var that = this;
    var my_audio = that.data.my_audio;
    innerAudioContext.src = my_audio;
    var already = that.data.already
    console.log(already)
    if (already==false){
      innerAudioContext.play();
      innerAudioContext.onPlay(() => {
        console.log('开始播放');
      })
      that.setData({
        already: true,
        hide: true,
      })
    }else{
      innerAudioContext.pause();
      // innerAudioContext.onStop(() => {
      //   console.log('录音播放停止');
      // })
      that.setData({
        already:false,
        hide: false,
      })
    }

    innerAudioContext.onEnded(() => {
      console.log('录音播放结束');
      that.setData({
        already: false,
        hide: false,
      })  
    })
  },
  // 播放音频
  audio:function(e){
    var that = this
    var a = that.data
    var audio_play = a.audio_play
    var audio_pause = a.audio_pause
    if (audio_play == false) {
      that.audioCtx.play()
      that.setData({
        audio_play:true
      })
    }else{
      that.audioCtx.pause()
      that.setData({
        audio_play: false,
      })
    }
  },
  //播放音频
  audios: function () {
    var that=this;
    console.log(that)
    var l_audio = that.data.task.voice;
    console.log(that.data.task.voice)
    innerAudioContext_con.autoplay = false;
    innerAudioContext_con.src =  l_audio;
    innerAudioContext_con.play();
    innerAudioContext_con.onPlay(() => {
      console.log('开始播放')
    })
    // if (that.data.answerState == 0) {
    //   that.setData({
    //     answerState: 1
    //   })
    //   innerAudioContext_con.play();
    //   innerAudioContext_con.onPlay(() => {
    //     console.log('开始播放')
    //   })
    // } else {
    //   that.setData({
    //     answerState: 0
    //   })
    //   innerAudioContext_con.pause();
    //   innerAudioContext_con.onStop(() => {
    //     console.log('录音播放停止');
    //   })
    // }
    innerAudioContext_con.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

  },
  //播放视频
  video:function(){
    this.videoContext.play()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    select.splice(0, select.length);
    //视频
    this.videoContext=wx.createVideoContext("videoId")
    this.audioCtx = wx.createAudioContext('myAudio')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})